<template>
  <div class="rating-system">
    <h3>我的评分</h3>
    <div class="rating-controls">
      <div class="stars">
        <span 
          v-for="star in 5" 
          :key="star" 
          class="star"
          :class="{ active: star <= currentRating }"
          @click="rateMovie(star)"
          @mouseover="hoverRating = star"
          @mouseleave="hoverRating = 0"
        >
          ⭐
        </span>
      </div>
      <span class="rating-text">
        {{ currentRating > 0 ? `已评分: ${currentRating}星` : '点击星星评分' }}
      </span>
      <button v-if="currentRating > 0" @click="removeRating" class="remove-rating">
        取消评分
      </button>
    </div>

    <!-- 评论系统 -->
    <div class="comment-section">
      <h4>发表评论</h4>
      <div v-if="userStore.isLoggedIn" class="comment-form">
        <textarea 
          v-model="commentText" 
          placeholder="分享你的观影感受..."
          maxlength="500"
          rows="4"
        ></textarea>
        <div class="comment-actions">
          <span class="char-count">{{ commentText.length }}/500</span>
          <button 
            @click="submitComment" 
            :disabled="!commentText.trim() || submitting"
            class="submit-comment"
          >
            {{ submitting ? '发布中...' : '发布评论' }}
          </button>
        </div>
      </div>
      <div v-else class="login-prompt">
        <p>请先登录以发表评论</p>
        <router-link to="/login" class="login-link">立即登录</router-link>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comments-list">
      <div v-for="comment in filteredComments" :key="comment.id" class="comment-item">
        <div class="comment-header">
          <span class="username">{{ comment.userName }}</span>
          <span class="comment-time">{{ comment.createdAt }}</span>
          <span v-if="comment.isOwn" class="own-comment">我的评论</span>
        </div>
        <div class="comment-content">{{ comment.content }}</div>
        <div v-if="comment.isOwn" class="comment-actions">
          <button @click="editComment(comment)" class="edit-btn">编辑</button>
          <button @click="deleteComment(comment.id)" class="delete-btn">删除</button>
        </div>
      </div>
    </div>

    <!-- 编辑评论弹窗 -->
    <div v-if="editingComment" class="modal-overlay" @click="cancelEdit">
      <div class="modal" @click.stop>
        <h4>编辑评论</h4>
        <textarea v-model="editingComment.content" rows="4" maxlength="500"></textarea>
        <div class="modal-actions">
          <button @click="saveEditedComment">保存</button>
          <button @click="cancelEdit" class="cancel">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '../store/user';
import { ElMessage, ElMessageBox } from 'element-plus';
import { commentService } from '../services/commentService';

const props = defineProps({
  movieId: {
    type: String,
    required: true
  }
});

const userStore = useUserStore();
const currentRating = ref(0);
const hoverRating = ref(0);
const commentText = ref('');
const submitting = ref(false);
const editingComment = ref(null);
const comments = ref([]);

// 加载评论列表
const loadComments = async () => {
  try {
    const response = await commentService.getCommentsByMovie(props.movieId,{status:"approved"});
    comments.value = response.data || [];
  } catch (error) {
    console.error('加载评论失败:', error);
    ElMessage.error('加载评论失败');
  }
};

const filteredComments = computed(() => {
  return comments.value.map(comment => ({
    ...comment,
    isOwn: comment.userId === userStore.userInfo?.userId
  })).sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
});

onMounted(async () => {
  // 加载用户评分
  if (userStore.isLoggedIn) {
    const userRating = userStore.userRatings[props.movieId];
    if (userRating) {
      currentRating.value = userRating.rating;
    }
  }

  // 加载评论数据
  await loadComments();
});

const rateMovie = (rating) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录以进行评分');
    return;
  }
  
  currentRating.value = rating;
  userStore.setRating(props.movieId, rating);
  ElMessage.success(`已评分 ${rating} 星`);
};

const removeRating = () => {
  currentRating.value = 0;
  userStore.removeRating(props.movieId);
};

const submitComment = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录');
    return;
  }

  if (!commentText.value.trim()) {
    ElMessage.warning('请输入评论内容');
    return;
  }

  submitting.value = true;

  try {
    // 防刷机制：检查最近评论频率
    const recentComments = comments.value.filter(comment => 
      comment.userId === userStore.userInfo.id && 
      Date.now() - new Date(comment.createdAt).getTime() < 60000 // 1分钟内
    );

    if (recentComments.length >= 3) {
      ElMessage.warning('评论过于频繁，请稍后再试');
      return;
    }

    const commentData = {
      content: commentText.value.trim(),
      movieId: props.movieId,
      userId: userStore.userInfo.userId,
      rating: currentRating.value || null,
      status:"pending"
    };

    await commentService.createComment(commentData);
    
    commentText.value = '';
    await loadComments(); // 重新加载评论列表
    
    ElMessage.success('评论已提交，等待审核通过');
  } catch (error) {
    console.error('评论发布失败:', error);
    ElMessage.error('评论发布失败');
  } finally {
    submitting.value = false;
  }
};

const editComment = (comment) => {
  editingComment.value = { ...comment };
};

const saveEditedComment = async () => {
  if (!editingComment.value.content.trim()) {
    ElMessage.warning('评论内容不能为空');
    return;
  }

  try {
    await commentService.updateComment(editingComment.value.id, {
      content: editingComment.value.content
    });
    
    await loadComments(); // 重新加载评论列表
    ElMessage.success('评论修改成功');
    editingComment.value = null;
  } catch (error) {
    console.error('评论修改失败:', error);
    ElMessage.error('评论修改失败');
  }
};

const deleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条评论吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    await commentService.deleteComment(commentId);
    await loadComments(); // 重新加载评论列表
    ElMessage.success('评论删除成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('评论删除失败:', error);
      ElMessage.error('评论删除失败');
    } else {
      ElMessage.info('已取消删除操作');
    }
  }
};

const cancelEdit = () => {
  editingComment.value = null;
};

const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};
</script>

<style scoped>
.rating-system {
  margin-top: 30px;
  padding: 20px;
  background: var(--card);
  border-radius: 8px;
}

.rating-controls {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.stars {
  display: flex;
  gap: 4px;
}

.star {
  font-size: 24px;
  cursor: pointer;
  opacity: 0.5;
  transition: all 0.2s;
}

.star.active, .star:hover {
  opacity: 1;
  transform: scale(1.1);
}

.rating-text {
  color: var(--muted);
}

.remove-rating {
  padding: 4px 8px;
  border: 1px solid #e53e3e;
  border-radius: 4px;
  background: transparent;
  color: #e53e3e;
  cursor: pointer;
  font-size: 12px;
}

.remove-rating:hover {
  background: #e53e3e;
  color: white;
}

.comment-section {
  margin-top: 20px;
}

.comment-form textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #2d3748;
  border-radius: 6px;
  background: #1a202c;
  color: var(--text);
  resize: vertical;
}

.comment-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.char-count {
  font-size: 12px;
  color: var(--muted);
}

.submit-comment {
  padding: 8px 16px;
  background: var(--primary);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-comment:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.login-prompt {
  text-align: center;
  padding: 20px;
  color: var(--muted);
}

.login-link {
  color: var(--primary);
  text-decoration: none;
}

.comments-list {
  margin-top: 20px;
}

.comment-item {
  padding: 16px;
  border-bottom: 1px solid #2d3748;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.username {
  font-weight: 600;
  color: var(--text);
}

.comment-time, .own-comment {
  font-size: 12px;
  color: var(--muted);
}

.own-comment {
  background: var(--primary);
  color: white;
  padding: 2px 6px;
  border-radius: 12px;
  font-size: 10px;
}

.comment-content {
  line-height: 1.5;
  color: var(--text);
}

.comment-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.edit-btn, .delete-btn {
  padding: 4px 8px;
  border: 1px solid #2d3748;
  border-radius: 4px;
  background: transparent;
  color: var(--text);
  cursor: pointer;
  font-size: 12px;
}

.delete-btn {
  border-color: #e53e3e;
  color: #e53e3e;
}

.delete-btn:hover {
  background: #e53e3e;
  color: white;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: var(--card);
  padding: 24px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
}

.modal h4 {
  margin-bottom: 16px;
}

.modal textarea {
  width: 100%;
  margin-bottom: 16px;
}

.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.modal-actions button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.modal-actions button:first-child {
  background: var(--primary);
  color: white;
}

.modal-actions .cancel {
  background: #4a5568;
  color: var(--text);
}
</style>